package app.auto.runner.base.bitmap;

import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.View;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import androidx.documentfile.provider.DocumentFile;

import app.auto.runner.base.framework.Init;
import app.auto.runner.base.utility.DocumentsUtils;
import app.auto.runner.base.utility.StorageUtil;

public class BitmapUtil {
    public static Bitmap roundBitmapByShader(Bitmap bitmap, int radius) {
        return getBitmapPrivate(bitmap, radius);
    }

    private static Bitmap getBitmapPrivate(Bitmap bitmap, int radius) {
        int outWidth = bitmap.getWidth();
        int outHeight = bitmap.getHeight();

        if (bitmap == null) {
            throw new NullPointerException("Bitmap can't be null");
        }
        // 初始化缩放比
        float widthScale = outWidth * 1.0f / bitmap.getWidth();
        float heightScale = outHeight * 1.0f / bitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.setScale(widthScale, heightScale);

        // 初始化绘制纹理图
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        // 根据控件大小对纹理图进行拉伸缩放处理
        bitmapShader.setLocalMatrix(matrix);

        // 初始化目标bitmap
        Bitmap targetBitmap = Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888);

        // 初始化目标画布
        Canvas targetCanvas = new Canvas(targetBitmap);

        // 初始化画笔
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(bitmapShader);

        // 利用画笔将纹理图绘制到画布上面
        targetCanvas.drawRoundRect(new RectF(0, 0, outWidth, outWidth), radius, radius, paint);

        return targetBitmap;
    }

    static Context ctx;

    public static void init(Context context) {
        ctx = context;
    }

    public static void saveBitmap(Bitmap bitmap, File file) {
        saveBitmap(ctx, bitmap, file);
    }

    public static void saveBitmap(Context ctx, Bitmap bitmap, File file) {
        saveByteOSToFile(ctx, compressImageTo(bitmap), file);
    }

    private static void saveByteOSToFile(Context ctx, ByteArrayOutputStream baos, File file) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file.getAbsolutePath());
            fileOutputStream.write(baos.toByteArray());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        if (bitmap != null) {
//            OutputStream outputStream;
//            if (!file.exists()) {
//                SharedPreferences perf = PreferenceManager.getDefaultSharedPreferences(ctx);
//                String path = perf.getString(StorageUtil.getPrimaryStoragePath(ctx), "");
//
////                DocumentsUtils.getDocumentFile(file, true, ctx);
//
////                DocumentFile.fromSingleUri(ctx,Uri.fromFile(file))
//
////                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
////                    DocumentsUtils.createFile(ctx, file);
//                //做一些处理
////                } else {
//
//                file.getParentFile().mkdirs();
//                try {
//                    file.createNewFile();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                //在版本低于此的时候，做一些处理
////                }
//            }
//            try {
////                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
////                    outputStream = DocumentsUtils.getOutputStream(ctx, file);
////                } else {
//                outputStream = new FileOutputStream(file);
////                }
//
//                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
////                bitmap.recycle();
//                outputStream.flush();
//                outputStream.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }

    private static void saveBitmapPrivate(Context ctx, Bitmap bitmap, File file) {
        if (bitmap != null) {
            OutputStream outputStream;
            if (!file.exists()) {
                SharedPreferences perf = PreferenceManager.getDefaultSharedPreferences(ctx);
                String path = perf.getString(StorageUtil.getPrimaryStoragePath(ctx), "");

//                DocumentsUtils.getDocumentFile(file, true, ctx);

//                DocumentFile.fromSingleUri(ctx,Uri.fromFile(file))

//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                    DocumentsUtils.createFile(ctx, file);
                //做一些处理
//                } else {

                file.getParentFile().mkdirs();
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //在版本低于此的时候，做一些处理
//                }
            }
            try {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                    outputStream = DocumentsUtils.getOutputStream(ctx, file);
//                } else {
                outputStream = new FileOutputStream(file);
//                }

                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
//                bitmap.recycle();
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static ByteArrayOutputStream compressImageTo(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 1024) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
//        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return baos;
    }

    public static Bitmap scale(Bitmap bitmap, float scale) {
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

    public static Bitmap getImageThumbnail(Context context, ContentResolver cr, String Imagepath) {
        ContentResolver testcr = context.getContentResolver();
        String[] projection = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID,};
        String whereClause = MediaStore.Images.Media.DATA + " = '" + Imagepath + "'";
        Cursor cursor = testcr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, whereClause, null, null);
        int _id = 0;
        String imagePath = "";
        if (cursor == null || cursor.getCount() == 0) {
            return null;
        } else if (cursor.moveToFirst()) {
            int _idColumn = cursor.getColumnIndex(MediaStore.Images.Media._ID);
            int _dataColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            do {
                _id = cursor.getInt(_idColumn);
                imagePath = cursor.getString(_dataColumn);
            } while (cursor.moveToNext());
        }
        cursor.close();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(cr, _id, MediaStore.Images.Thumbnails.MINI_KIND, options);
        return bitmap;
    }

    public static Bitmap compressImage(Bitmap image) {
        return getBitmapPrivate(image);
    }

    private static Bitmap getBitmapPrivate(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 250) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            if (options <= 40) {
                break;
            }
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    public static Bitmap viewConversionBitmap(View v) {
        return getBitmapPrivate(v);
    }

    private static Bitmap getBitmapPrivate(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.TRANSPARENT);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }
}
